package com.hshx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hshx.VO.DeptVo;
import com.hshx.pojo.Dept;
import com.hshx.pojo.Role;
import com.hshx.pojo.Users;
import com.hshx.service.DeptService;
import com.hshx.service.IMessageProduceService;
import com.hshx.service.RoleService;
import com.hshx.service.UsersService;
import com.hshx.util.RedisUtil1;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RequestMapping("/systemService")
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisUtil1 redisUtil1;
    @Autowired
    private IMessageProduceService service;

    /**
     * 获取所有部门信息
     * @return
     */
    @RequestMapping("/getAllDept")
    public List<Dept> getAllDept(){
        return deptService.list();
    }

    /**
     * 新增一个部门
     * @param dept
     * @return
     */
    @RequestMapping("/addDept")
    public boolean addDept(@SpringQueryMap Dept dept){
        if(deptService.save(dept)){
            this.service.send("direct","flushDept","flushDeptRedis,");
            return true;
        }
        return false;
    }

    /**
     * 从数据库移除一个部门
     * @param dept_id
     * @return
     */
    @RequestMapping("/removeDept")
    public boolean removeDept(int dept_id){
        if(usersService.count(new QueryWrapper<Users>().eq("users_dept",dept_id))>0){
            return false;
        }
        if(deptService.removeById(dept_id)){
            this.service.send("direct","flushDept","flushDeptRedis,");
            return true;
        }
        return false;
    }

    /**
     * 修改某个部门信息
     * @param dept
     * @return
     */
    @RequestMapping("/updateDept")
    public boolean updateDept(@SpringQueryMap Dept dept){
        if(usersService.count(new QueryWrapper<Users>().eq("users_dept",dept.getDept_id()))>0&&dept.getDept_state()!=1){
            return false;
        }
        if(deptService.updateById(dept)){
            this.service.send("direct","flushDept","flushDeptRedis,");
            return true;
        }
        return false;
    }

    /**
     * 获取单个部门信息
     * @param dept_id
     * @return
     */
    @RequestMapping("/getDeptOne")
    public Dept getDeptOne(int dept_id){
        return deptService.getById(dept_id);
    }

    /**
     * 获取所有启用的部门集合
     * @return
     */
    @RequestMapping("/getDeptList")
    public List<Dept> getDeptList(){
        List<Object> objects = redisUtil1.lRange("DeptRedisList", 0, -1);
        if(objects!=null&&objects.size()>0){
            return objects.stream().map(o->((Dept)o)).collect(Collectors.toList());
        }
        List<Dept> deptList = deptService.list(new QueryWrapper<Dept>().eq("dept_state",1));
        redisUtil1.lPushAll("DeptRedisList",deptList,60L*24);
        return deptList;
    }

    @RequestMapping("/getDeptPage")
    public Map<String,Object> getDeptPage(Integer page, Integer limit){
//        Integer limit=pageSize;
//        Integer page=pageIndex;
        HashMap<String, Object> deptMap = new HashMap<>();
        if(page==null||page<=0){
            page=1;
        }
        if(limit==null||limit<=0){
            limit=10;
        }
        List<Object> objects = redisUtil1.lRange("deptAll",0,-1);
        if(objects!=null&&objects.size()>0){
            System.out.println("redis中存在");

            List<Dept> deptList= objects.stream().map(o->((Dept)o)).collect(Collectors.toList());
            deptMap.put("code", 0);
            deptMap.put("limit",limit);
            deptMap.put("pages", deptList.size()%limit==0?deptList.size()/limit:deptList.size()/limit+1);
            deptMap.put("pageNum",page);
            deptMap.put("data", deptList.stream().sorted(Comparator.comparing(Dept::getDept_id).reversed()).skip((page-1)*limit).limit(limit).collect(Collectors.toList()));
            System.out.println(deptMap.get("data").toString());
            deptMap.put("count", deptList.size());
        }else{//redis中不存在或失效
            System.out.println("redis中不存在或失效");

            List<Dept> deptList=deptService.list(new QueryWrapper<Dept>().orderByDesc("dept_id"));
            redisUtil1.lPushAll("deptAll",deptList,24*60L);
            deptMap.put("code", 0);
            deptMap.put("limit",limit);
            deptMap.put("data", deptList.stream().sorted(Comparator.comparing(Dept::getDept_id).reversed()).skip((page-1)*limit).limit(limit).collect(Collectors.toList()));
            deptMap.put("count", deptList.size());
        }
        return deptMap;
    }

    @RequestMapping("/hasDeptName")
    public boolean hasDeptName(String dept_name){
        return deptService.count(new QueryWrapper<Dept>().eq("dept_name", dept_name))==0;
    }

    @RequestMapping("/getDeptVoList")
    public List<DeptVo> getDeptVoList(){
        List<Dept> deptList = deptService.list(new QueryWrapper<Dept>().eq("dept_state", 1));
        if(deptList==null||deptList.size()==0){
            return null;
        }
        List<DeptVo> deptVoList = new ArrayList<>();
        deptList.forEach(dept -> {
            DeptVo deptVo=new DeptVo();
            deptVo.setDeptName(dept.getDept_name());
            long num=usersService.count(new QueryWrapper<Users>().eq("users_dept",dept.getDept_id()));
            deptVo.setDeptNum(num);
            deptVoList.add(deptVo);
        });
        return deptVoList;
    }





    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "flushDept",durable = "true",autoDelete = "true"),
            exchange = @Exchange(value = "direct",type = ExchangeTypes.DIRECT),
            key = "flushDept"
    ))
    public void flushDept(String msg){
        System.out.println(msg);
        List<String> excute=Arrays.asList(msg.split(","));
        excute.forEach(e->{
            if("flushDeptRedis".equals(e)){
                System.out.println("============执行flushDeptRedis=============");
                flushDeptRedis();
            }
            if("flushUsersVoRedis".equals(e)){
                System.out.println("============执行flushUsersVoRedis=============");
                flushUsersVoRedis();
            }
        });
    }

    private void flushDeptRedis(){
        redisUtil1.remove("deptAll");
        redisUtil1.lPushAll("deptAll",deptService.list(new QueryWrapper<Dept>().orderByDesc("dept_id")),24*60L);
        redisUtil1.remove("DeptRedisList");
        redisUtil1.lPushAll("DeptRedisList",deptService.list(new QueryWrapper<Dept>().eq("dept_state",1)),60L*24);
    }

    private void flushUsersVoRedis(){
        redisUtil1.remove("usersRedisList");
        redisUtil1.lPushAll("usersRedisList",usersService.list(new QueryWrapper<Users>().orderByDesc("users_id")),60L*24);
//        redisUtil1.remove("UsersVoList");
//        redisUtil1.lPushAll("UsersVoList",usersService.getAllUsersVo(),60L*24);
    }
}
